﻿using Rookey.Frame.IMCore;
using Rookey.Frame.IMCore.IO;
using Rookey.Frame.Operate.Base.OperateHandle;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI.HtmlControls;

namespace Rookey.Frame.IMOperate
{
    /// <summary>
    /// 用户操作处理类
    /// </summary>
    public class UserOperateHandle : IUserOperateHandle
    {
        /// <summary>
        /// 登录成功后，登录IM
        /// </summary>
        /// <param name="session">session</param>
        /// <param name="request">request</param>
        /// <param name="response">response</param>
        /// <param name="username">用户名</param>
        /// <param name="pwd">密码</param>
        /// <param name="expires">有效时间（分钟）</param>
        public void AfterLoginSuccess(HttpSessionStateBase session, HttpRequestBase request, HttpResponseBase response, string username, string pwd, int expires)
        {
            if (AccountImpl.Instance.Validate(username, pwd))
            {
                string[] UserDirs = new string[] { "Config", "Home", "pub", "Temp" };
                foreach (string dir in UserDirs)
                {
                    String path = String.Format("/{0}/{1}", username, dir);
                    if (!Directory.Exists(path)) Directory.CreateDirectory(path);
                }
                String sessionId = Guid.NewGuid().ToString().ToUpper();
                ServerImpl.Instance.Login(sessionId, request.RequestContext.HttpContext.ApplicationInstance.Context, username, DateTime.Now.AddMinutes(expires));
            }
        }

        /// <summary>
        /// 注册用户后操作
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="pwd">密码</param>
        public void AfterRegiterUser(string username, string pwd)
        {
            if (AccountImpl.Instance.GetUserInfo(username) == null)
            {
                AccountImpl.Instance.CreateUser(username, username, pwd, string.Empty);
            }
        }

        /// <summary>
        /// 修改密码后操作
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="oldPwd">旧密码</param>
        /// <param name="newPwd">新密码</param>
        public void AfterChangePwd(string username, string oldPwd, string newPwd)
        {
            Hashtable hashInfo = new Hashtable();
            hashInfo.Add("PreviousPassword", oldPwd);
            hashInfo.Add("Password", newPwd);
            AccountImpl.Instance.UpdateUserInfo(username, hashInfo);
        }

        /// <summary>
        /// 删除用户后同时删除IM用户
        /// </summary>
        /// <param name="username"></param>
        public void AfterDeleteUser(string username)
        {
            AccountImpl.Instance.DeleteUser(username);
        }
    }
}
